import React, { useEffect, useRef, useState } from 'react'
import { SearchBar } from 'antd-mobile'
import styles from './index.module.scss'
import { getCurrentCity } from '@/utils/city'
import { searchCommunity } from '@/api/rent'
import { connect } from 'react-redux'
import { setCommunity } from '@/store/actionCreators'
import debounce from 'lodash/debounce'

function RentSearch ({ history, setCommunityData }) {
  const [communityList, setCommunityList] = useState(null)

  // 自定义防抖函数
  /**
  const myDebounce = (fn, delay = 200) => {
    let timer = null
    return function () {
      if (timer) clearTimeout(timer)
      timer = setTimeout(() => {
        fn.apply(this, arguments)
        timer = null
      }, delay)
    }
  }
   */

  const debounceRef = useRef()

  useEffect(() => {
    // debounceRef.current = myDebounce(search, 500)

    debounceRef.current = debounce(search, 500)
  }, [])

  const onChange = name => {
    debounceRef.current(name)
  }

  const search = async name => {
    const { value: id } = await getCurrentCity()

    const res = await searchCommunity({ id, name })

    setCommunityList(res.data.body)
  }

  const toggleSelect = ({ community, communityName }) => {
    setCommunityData({ community, communityName })

    history.goBack()
  }

  return (
    <div className={styles.root}>
      <SearchBar
        onChange={onChange}
        onCancel={() => history.goBack()}
        placeholder='请输入小区或地址'
      />
      {communityList && (
        <ul className={styles.tips}>
          {communityList.map(item => {
            return (
              <li
                key={item.community}
                className={styles.tip}
                onClick={() => toggleSelect(item)}
              >
                {item.communityName}
              </li>
            )
          })}
        </ul>
      )}
    </div>
  )
}

const mapDispatchToProps = dispatch => {
  return {
    setCommunityData (community) {
      dispatch(setCommunity(community))
    }
  }
}

export default connect(null, mapDispatchToProps)(RentSearch)
